package com.sunshine.lnuplus.view.Login;

import android.annotation.SuppressLint;
import android.app.Application;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.sunshine.lnuplus.utils.DatabaseHelper;

import org.jetbrains.annotations.NotNull;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class LoginViewModel extends AndroidViewModel {
    private MutableLiveData<Integer> resultData;

    public LoginViewModel(@NonNull Application application) {
        super(application);
        resultData = new MutableLiveData<>();
        resultData.setValue(0);
    }

    public MutableLiveData<Integer> getResultData() {
        return resultData;
    }

    public void toLogin(final Context context, String account, String password) {
        OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                .followRedirects(false)
                .build();
        RequestBody requestBody = new FormBody.Builder()
                .add("stuid", account)
                .add("pwd", password)
                .build();
        Request request = new Request.Builder()
                .url("http://jwgl.lnu.edu.cn/pls/wwwbks/bks_login2.login")
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Looper.prepare();
                handler.sendEmptyMessage(-1);//无网络
                Looper.loop();
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) {
                Headers headers = response.headers();
                String cookie = null;
                for (int i = 0; i < headers.size(); i++) {
                    if(headers.name(i).equals("Set-Cookie")){
                        cookie = headers.value(i);
                    }
                }
                if(cookie!=null){
                    getClasses(context,cookie);
                }else {
                    Looper.prepare();
                    handler.sendEmptyMessage(-2); //账号或者密码不正确
                    Looper.loop();
                }
            }
        });
    }

    private void getClasses(final Context context, String cookie){
        final String url = "http://jwgl.lnu.edu.cn/pls/wwwbks/xk.CourseView";
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .header("Cookie",cookie)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Looper.prepare();
                handler.sendEmptyMessage(-3);  //课程解析失败
                Looper.loop();
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                Looper.prepare();
                resolveTimetable(context,response.body().string());
                Looper.loop();
            }
        });
    }

    private void resolveTimetable(Context context, String result){
        Document document = Jsoup.parse(result);
        Elements timetable = document.select("td[bgcolor=\"#EAE2F3\"]");    //筛选字标签，此标签为课程信息
        resolveClasses(context,timetable);
        resolveTeacher(context,timetable);
        handler.sendEmptyMessage(1);
    }

    private void resolveTeacher(Context context, Elements elements) {
        int count = 0;  //筛选，小于50用于解析教师，大于50用于解析课程具体信息
        for (Element element : elements) {
            if (++count < 50) {
                String[] teacherInfo;
                String info = element.toString();
                info = info
                        .replace("<td bgcolor=\"#EAE2F3\"><p align=\"center\">", "")
                        .replace("<br>", "")
                        .replaceAll("<font color=\"#FF0000\">(.*)</font>", "")
                        .replace("&nbsp;</p></td>", "")
                        .replace(" ", "")
                        .replace("(必修)", "")
                        .replace("(限选)", "")
                        .replace("(任选)", "");
                //判断当前时间是否有课
                if (!Objects.equals(info, "")) {
                    teacherInfo = info.split("/");
                    DatabaseHelper.updateTeacher(context,teacherInfo[0],teacherInfo[1]);
                }
            }
        }
    }

    private void resolveClasses(Context context, Elements elements){
        int count = 0;  //筛选，小于50用于解析教师，大于50用于解析课程具体信息
        String[] classInfo = new String[4];
        for(Element element:elements){
            if(++count>=50){
                String info;
                info = element.toString();
                info = info
                        .replace("<td bgcolor=\"#EAE2F3\"><p align=\"center\">","")
                        .replace("<br>","")
                        .replaceAll("<font color=\"#FF0000\">(.*)</font>", "")
                        .replace("&nbsp;</p></td>","")
                        .replace("全周上课","1-16")
                        .replace("单周上课","1,3,5,7,9,11,13,15")
                        .replace("双周上课","2,4,6,8,10,12,14,16")
                        .replace("周上","");
                switch ((count-50)%9){
                    case 0:classInfo[0] = info;
                        break;
                    case 6:classInfo[2] = info;
                        break;
                    case 7:classInfo[1] = info;
                        break;
                    case 8:classInfo[3] = info;
                        DatabaseHelper.addTimetableToDB(context,classInfo[0],classInfo[1],null,classInfo[2],"0",classInfo[3]);
                }
            }
        }
    }

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case -1:resultData.setValue(-1);break;
                case -2:resultData.setValue(-2);break;
                case -3:resultData.setValue(-3);break;
                case 1:resultData.setValue(1);
            }
        }
    };
}
